import axios from 'axios'
import { Message, Loading } from 'element-ui'
import { removeToken } from '@/utils/auth'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_PREFIX, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  crossDomain: true,
  timeout: 30000 // request timeout
})

let requestLoading

const loadList = [
  '530012', '530058'
]
let urlc
// request interceptor
service.interceptors.request.use(
  config => {
    // console.log(config);
    const shopId = sessionStorage.getItem('shopId')
    urlc = config.url.split('do?c=')[1]
    if (shopId && shopId !== 'null' && shopId !== 'undefined') {
      const noGymId = []
      // 加载
      if (loadList.includes(urlc)) {
        requestLoading = Loading.service()
      }
      config.headers.version = 'DD_1.5.5'
      // do something before request is sent'420002',
      // requestLoading = Loading.service()
      // // 临时参数
      // config.url = config.url + '&isTest=1'
      config.headers.shopId = sessionStorage.getItem('shopId')
      if (noGymId.includes(urlc)) {
        config.headers.gymId = sessionStorage.getItem('venueId')
      }
      return config
    } else {
      Message.error('没有shopId')
    }
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    if (loadList.includes(urlc)) {
      requestLoading.close()
    }

    if (res.errorCode !== '000000' && res.success !== true) {
      Message({
        message: res.errorMsg || 'Error',
        type: 'error',
        duration: 3 * 1000
      })
      if (res.errorCode === '00016' || res.errorCode === '00068') {
        removeToken()
        // debugger
        const shopId = sessionStorage.getItem('shopId') || 1
        sessionStorage.clear()
        localStorage.clear()
        sessionStorage.setItem('shopId', shopId)
        router.replace(`/login?shopId=${shopId}`)
      }
      return Promise.reject(new Error(res.errorMsg || 'Error'))
    } else {
      return Promise.resolve(res)
    }
  },
  error => {
    if (loadList.includes(urlc)) {
      requestLoading.close()
    }
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
